<template>
	<div class="app-container">
		<div class="filter-container">
			<el-input v-model="listQuery.typeCode" placeholder="请输入字典代码" style="width: 200px;" class="filter-item"
				@keyup.enter.native="handleFilter" />
			<el-input v-model="listQuery.typeName" placeholder="类型名称支持模糊查询" style="width: 200px;" class="filter-item"
				@keyup.enter.native="handleFilter" />
			<el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
				查询
			</el-button>
			<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
				@click="handleCreate">
				新增
			</el-button>

		</div>

		<el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
			style="width: 100%;" @sort-change="sortChange">
			<el-table-column label="ID" prop="id" sortable="custom" align="center" width="60"
				:class-name="getSortClass('id')">
				<template slot-scope="{row}">
					<span>{{ row.id }}</span>
				</template>
			</el-table-column>

			<el-table-column label="字典代码" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.typeCode }}</span>
				</template>
			</el-table-column>
			<el-table-column label="类型名称" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.typeName }}</span>
				</template>
			</el-table-column>
			<el-table-column label="值编号" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.valueId }}</span>
				</template>
			</el-table-column>
			<el-table-column label="值名称" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.valueName }}</span>
				</template>
			</el-table-column>
			<el-table-column label="创建者编号" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.createBy }}</span>
				</template>
			</el-table-column>

			<el-table-column label="创建日期" width="100px" align="center" prop='createDate'
				:formatter='dateFormatter'></el-table-column>

			<el-table-column label="修改者编号" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.modifyBy }}</span>
				</template>
			</el-table-column>

			<el-table-column label="修改日期" width="100px" align="center" prop='modifyDate'
				:formatter='dateFormatter'></el-table-column>

			<el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
				<template slot-scope="{row,$index}">
					<el-button type="primary" size="mini" @click="handleUpdate(row)">
						编辑
					</el-button>
					<el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
			@pagination="getList" />

		<!-- 抽屉模态框 -->
		<el-drawer :title="dr_title" :visible.sync="dialog" :before-close="handleClose" direction="rtl"
			custom-class="demo-drawer" size="35%">
			<div class="demo-drawer__content">
				<el-form :model="form" ref="form" :rules="rules">
					<el-form-item v-if='show_id_item' label="编号ID" :label-width="formLabelWidth">
						<el-input v-model="form.id" :readonly='true'></el-input>
					</el-form-item>
					<el-form-item label="字典代码" :label-width="formLabelWidth" prop="typeCode">
						<el-input v-model="form.typeCode"></el-input>
					</el-form-item>
					<el-form-item label="类型名称" :label-width="formLabelWidth" prop="typeName">
						<el-input v-model="form.typeName"></el-input>
					</el-form-item>
					<el-form-item label="值编号" :label-width="formLabelWidth" prop="valueId">
						<el-input v-model="form.valueId"></el-input>
					</el-form-item>
					<el-form-item label="值名称" :label-width="formLabelWidth" prop="valueName">
						<el-input v-model="form.valueName"></el-input>
					</el-form-item>


				</el-form>
				<div class="demo-drawer__footer">
					<el-button icon="el-icon-error" @click="cancelForm">取 消</el-button>
					<el-button icon="el-icon-refresh-right" type="warning" @click="resetForm('form')">重置</el-button>
					<el-button icon="el-icon-check" type="success" @click="handleClose('form')"
						:loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
				</div>
			</div>
		</el-drawer>

	</div>
</template>

<script>
	import {
		fetchPage,
		del,
		add,
		update
	} from '@/api/dictApi';

	import {
		fetchDictList
	} from '@/api/dictApi'

	import waves from '@/directive/waves' // waves directive
	import {
		parseTime
	} from '@/utils'

	import {
		getToken
	} from '@/utils/auth'

	import Pagination from '@/components/Pagination' // secondary package based on el-pagination


	export default {
		name: 'ComplexTable',
		components: {
			Pagination
		},
		directives: {
			waves
		},
		filters: {
			statusFilter(status) {
				const statusMap = {
					Y: 'success',
					N: 'danger'
				}
				return statusMap[status]
			},
			typeFilter(type) {
				return calendarTypeKeyValue[type]
			}
		},
		data() {
			return {
				tableKey: 0,
				list: null,
				total: 0,
				listLoading: true,
				listQuery: {
					pageNo: 1,
					pageSize: 10,
					typeCode: '',
					typeName: '',
					sort: '+id'
				},

				sortOptions: [{
					label: 'ID Ascending',
					key: '+id'
				}, {
					label: 'ID Descending',
					key: '-id'
				}],
				temp: {
					id: undefined,
					importance: 1,
					remark: '',
					timestamp: new Date(),
					title: '',
					type: '',
					status: 'published'
				},

				rules: {
					typeCode: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					typeName: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					valueId: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					valueName: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}]
				},
				dialog: false,
				loading: false,
				form: {
					id: '',
					typeCode: '',
					typeName: '',
					valueId: '',
					valueName: '',
					createBy: '',
					createDate: '',
					modifyBy: '',
					modifyDate: ''
				},
				formLabelWidth: '80px',
				dr_title: '',
				show_id_item: false,
				file: "",
			}
		},
		created() {
			this.getList();
		},
		methods: {
			getList() {
				this.listLoading = true
				fetchPage(this.listQuery).then(response => {
					console.info('response==>', response)
					this.list = response.data.records;
					this.total = response.data.total;

					// Just to simulate the time of the request
					setTimeout(() => {
						this.listLoading = false
					}, 1.5 * 1000)
				})
			},

			dateFormatter(row, column, cellValue, index) {
				if (cellValue != null) {
					return cellValue.substring(0, 10);
				}
			},

			handleFilter() {
				this.listQuery.page = 1
				this.getList()
			},

			sortChange(data) {
				const {
					prop,
					order
				} = data;
				if (prop === 'id') {
					this.sortByID(order)
				}
			},
			sortByID(order) {
				if (order === 'ascending') {
					this.listQuery.sort = '+id'
				} else {
					this.listQuery.sort = '-id'
				}
				this.handleFilter()
			},
			resetTemp() {
				this.temp = {
					id: undefined,
					importance: 1,
					remark: '',
					timestamp: new Date(),
					title: '',
					status: 'published',
					type: ''
				}
			},
			handleCreate() {
				this.dr_title = '新增数据';
				this.dialog = true;
				this.show_id_item = false;
				this.clearForm();
			},
			clearForm() {
				this.form = {
					id: '',
					typeCode: '',
					typeName: '',
					valueId: '',
					valueName: ''
				}
				this.picUrl = '';
			},

			handleUpdate(row) {
				this.dr_title = '编辑数据';
				this.dialog = true;
				this.show_id_item = true;
				console.info('row=>', row);
				this.clearForm();
				this.form = {
					id: row.id,
					typeCode: row.typeCode,
					typeName: row.typeName,
					valueId: row.valueId,
					valueName: row.valueName
				};

			},

			handleDelete(row, index) {
				this.$confirm('此操作将永久删除编号为' + row.id + '的数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					del(row.id).then(res => {
						if (res.code == '201') {
							this.$message({
								message: res.msg,
								type: 'success'
							});
						} else {
							this.$message.error(res.msg);
						}
					}).catch(err => {
						console.error(err);
						this.$message.error('操作异常，请联系管理员！');
					})

					this.list.splice(index, 1)
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},

			getSortClass: function(key) {
				const sort = this.listQuery.sort
				return sort === `+${key}` ? 'ascending' : 'descending'
			},

			handleClose(formName) {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.$confirm('确定要提交表单吗？')
							.then(() => {
								this.loading = true;
								if (this.form.id == '') {
									this.insert();
								} else {
									this.edit();
								}
								this.loading = false;
								this.dialog = false;
							})
							.catch((err) => {
								console.log('error submit!!');
							});

					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			cancelForm() {
				this.loading = false;
				this.dialog = false;
				this.$refs['form'].resetFields();
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},

			formatDate(date) {
				let yyyy = date.getFullYear();
				let mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
				let dd = String(date.getDate()).padStart(2, '0');
				let hh = String(date.getHours()).padStart(2, '0');
				let min = String(date.getMinutes()).padStart(2, '0');
				let ss = String(date.getSeconds()).padStart(2, '0');
				return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`;
			},

			insert() {
				this.form.createBy = getToken();
				this.form.createDate = this.formatDate(new Date());

				add(this.form).then(res => {
					if (res.code == '201') {
						this.$message({
							message: res.msg,
							type: 'success'
						});
						this.getList();
					} else {
						this.$message.error(res.msg);
					}
				}).catch(err => {
					console.error(err);
					this.$message.error('操作异常，请联系管理员！');
				})
			},
			edit() {
				this.form.modifyBy = getToken();
				this.form.modifyDate = this.formatDate(new Date());
				update(this.form).then(res => {
					if (res.code == '201') {
						this.$message({
							message: res.msg,
							type: 'success'
						});
						this.getList();
					} else {
						this.$message.error(res.msg);
					}
				}).catch(err => {
					console.error(err);
					this.$message.error('操作异常，请联系管理员！');
				})
			}
		}
	}
</script>

<style scoped>
	.demo-drawer__footer {
		display: flex;
		margin: 0 30px;
	}

	.demo-drawer__footer button {
		flex: 1;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 58px;
		height: 58px;
		border: 1px solid;
		line-height: 58px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>